<template>
  <el-dialog :title="`${data.id?'编辑':'添加'}房产`" :visible="isShowDialog" destroy-on-close @close="btnClose">
    <el-form ref="form" :model="data" :rules="rules">
      <el-form-item label="经纪">
        <el-select v-model="data.agent">
          <el-option
            v-for="agent in agents"
            :key="agent.id"
            :value="agent.id"
            :label="agent.name"
          />
        </el-select>
        <el-form-item label="分类">
          <el-select v-model="data.category">
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :value="category.id"
              :label="category.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="data.title" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-row type="flex">
            <el-cascader
              v-model="value"
              style="width: 140px"
              placeholder="选择区域"
              :options="areas"
              @change="(res)=>{
                data.address = res.join(',')
                value = []
                $refs.areaInput.focus()
              }"
            />
            <el-input ref="areaInput" v-model="data.address" />
          </el-row>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="data.price" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="data.desc" :autosize="{ minRows: 4, maxRows: 8}" resize="none" type="textarea" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <template>
            <div id="app">
              <VueEditor :config="config" />
            </div>
          </template>
        </el-form-item>
        <el-form-item label="介绍图片">
          <div style="padding-left:40px">
            <ImageUpload ref="photos" :single="false" />
          </div>
        </el-form-item>
        <el-form-item label="封面">
          <div style="padding-left:40px">
            <ImageUpload ref="upload" />
          </div>
        </el-form-item>
      </el-form-item></el-form>
    <template #footer>
      <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      <el-button size="small" @click="btnClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Axios from 'axios'
import VueEditor from 'vue-word-editor'
import 'quill/dist/quill.snow.css'
import { getProperties, delProperty, addProperty, getPropertyDetail, updateProperty, getPropertiesCount } from '@/api/property'
import { getAgents } from '@/api/agent'
export default {
  name: 'App',
  components: { VueEditor },
  props: {
    categoryList: {
      type: Array,
      required: true
    },

    isShowDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      searchOptionConfirmed: {
        title: '',
        agent: ''
      },
      config: {
      // 上传图片的配置
        uploadImage: {
          url: 'http://localhost:3000/upload',
          name: 'file',
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.url)
          }
        },

        // 上传视频的配置
        uploadVideo: {
          url: 'http://localhost:3000/upload',
          name: 'file',
          uploadSuccess(res, insert) {
            insert('http://localhost:3000' + res.data.url)
          }
        }
      },
      value: '',
      agents: [],
      areas: [],
      dynamicTags: [],
      change: {},
      data: {
        category: '',
        title: '',
        desc: '',
        id: '',
        tag: '',
        address: '',
        price: '',
        content: '',
        agent: '',
        image: ''
      },
      inputVisible: true,
      inputValue: '',
      rules: {
        title: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    async change() {
      console.log(this.data.id)
      const res = await getPropertyDetail(this.data.id)
      this.data = {
        ...res.data,
        agent: res.data.agent?.id
      }
      this.dynamicTags = res.data.tags
      console.log(res, 273)
      this.$nextTick(() => {
        if (this.data.image) {
          this.$refs.upload.fileList = [
            { url: this.data.image }
          ]
        }
        if (this.data.photos?.length > 0) {
          this.$refs.photos.fileList = this.data.photos.map(url => ({ url }))
        }
      })
    }
  },
  async created() {
    await this.getAgents()
    const res = await Axios.get('https://restapi.amap.com/v3/config/district?key=60e00996dec1e73abda4333570328ef8&subdistrict=3')
    this.areas = res.data.districts[0].districts.map(area => {
    //   console.log(area)
      return {
        value: area.name,
        label: area.name,
        children: area.districts.map(area => {
          return {
            value: area.name,
            label: area.name,
            children: area.districts.map(area => {
              return {
                value: area.name,
                label: area.name
              }
            })
          }
        })
      }
    })
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },

    async getAgents() {
      const { data } = await getAgents({
        _limit: -1
      })
      this.agents = data
      console.log(1234, this.agents)
    },
    async delProperty(id) {
      await this.$confirm('确认删除?')
      await delProperty(id)
      this.$message.success('删除成功')
      this.getProperties()
    },
    // 编辑
    async updateProperty(id) {
      console.log(208, id)
      const res = await getPropertyDetail(id)
      console.log(205, res)
      this.data = {
        ...res,
        agent: res.agent?.id
      }
      console.log(215, this.data)
      this.dynamicTags = this.data.tags ? [...this.data.tags] : []
      console.log(239, this.dynamicTags)
      this.$parent.isShowDialog = true
      this.$nextTick(() => {
        if (this.data.image) {
          this.$refs.upload.fileList = [
            { url: this.data.image }
          ]
        }
        if (this.data.photos?.length > 0) {
          this.$refs.photos.fileList = this.data.photos.map(url => ({ url }))
        }
      })
    },
    async btnOK() {
      await this.$refs.form.validate()
      this.data.image = this.$refs.upload.fileList[0]?.url
      this.data.photos = this.$refs.photos.fileList?.map(img => img.url)
      this.data.tags = [...this.dynamicTags]
      if (this.data.id) {
        await updateProperty(this.data)
      } else {
        await addProperty(this.data)
      }
      this.$message.success('操作成功')
      this.$parent.isShowDialog = false
      this.$emit('update')
    },
    btnClose() {
      this.data = {}
      this.dynamicTags = []
      this.$parent.isShowDialog = false
    },
    async getProperties() {
      const { data } = await getProperties({
        ...this.pagination,
        ...this.searchOptionConfirmed
      })
      this.properties = data
      console.log(256, this.properties)
      const res = await getPropertiesCount()
      this.total = res.data
      console.log(this.total, 256)
    }
  }
}
</script>

<style lang="scss">
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>

